package com.lcf.framework.utils;

import com.lcf.framework.exception.SysException;
import com.lcf.framework.model.sms.SmsReq;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;

import java.util.function.Consumer;

/**
 * 短信
 * @author lcf
 */
public class SmsUtils {
    /**
     * 发国内短信
     */
    public static void send(SmsReq smsReq) {
        send(smsReq, null);
    }

    /**
     * 发国内短信
     */
    public static void send(SmsReq smsReq, Consumer<SendSmsResponse> callback) {
        // 初始化凭证
        Credential cred = new Credential(smsReq.getSecretId(), smsReq.getSecretKey());
        // 创建 SMS 客户端实例
        SmsClient smsClient = new SmsClient(cred, smsReq.getRegion());

        // 构造请求对象
        SendSmsRequest req = new SendSmsRequest();
        // 目标手机号（带国际码）
        String[] phone = smsReq.getPhone().stream()
                .map(x -> x.startsWith(smsReq.getInternationalCode()) ? x : smsReq.getInternationalCode() + x)
                .toList().toArray(new String[0]);
        req.setPhoneNumberSet(phone);
        // 应用 ID（控制台获取）
        req.setSmsSdkAppid(smsReq.getAppId());
        // 已审核通过的短信签名
        req.setSign(smsReq.getSignName());
        // 已审核通过的模板 ID
        req.setTemplateID(smsReq.getTemplateId());
        // 模板参数（按模板要求填写）
        req.setTemplateParamSet(smsReq.getTemplateParam().toArray(new String[0]));

        try {
            SendSmsResponse resp = smsClient.SendSms(req);
            if (callback != null) {
                callback.accept(resp);
            }
        } catch (TencentCloudSDKException e) {
            throw new SysException(e);
        }
    }
}
